/**
 * @file execution.cpp
 * @brief 订单执行相关实现
 * @details 实现了智能订单路由器和订单管理器的核心功能
 */

#include "execution/execution_types.h"
#include "execution/execution.h"
#include "execution/simulation_engine.h"
#include <sstream>
#include <iomanip>
#include <chrono>
#include <spdlog/spdlog.h>
#include <algorithm>
#include <mutex>

namespace hft {

/**
 * @brief 智能订单路由器构造函数
 * @param executor 订单执行器指针
 * @details 初始化订单路由器，设置默认的滑点和流动性限制
 */
SmartOrderRouter::SmartOrderRouter(std::shared_ptr<OrderExecutor> executor)
    : executor_(executor)
    , max_slippage_(0.001)  // 默认最大滑点0.1%
    , min_liquidity_(1000)  // 默认最小流动性要求
{}

/**
 * @brief 路由订单
 * @param order 待路由的订单
 * @return 如果订单成功路由返回true，否则返回false
 * @details 检查订单的流动性和滑点，如果满足条件则提交订单
 */
bool SmartOrderRouter::routeOrder(const Order& order) {
    // 先获取订单簿的快照，减少锁持有时间
    OrderBook book;
    {
        std::lock_guard<std::mutex> lock(books_mutex_);
        auto it = order_books_.find(order.symbol);
        if (it == order_books_.end()) {
            spdlog::warn("No order book available for symbol: {}", order.symbol);
            return false;
        }
        book = it->second;
    }
    
    // 检查流动性和滑点
    if (!checkLiquidity(order, book)) {
        spdlog::warn("Insufficient liquidity for order: {}", order.order_id);
        return false;
    }
    
    if (!checkSlippage(order, book)) {
        spdlog::warn("Slippage too large for order: {}", order.order_id);
        return false;
    }
    
    // 提交订单
    try {
        return executor_->submitOrder(order);
    } catch (const std::exception& e) {
        spdlog::error("Failed to submit order {}: {}", order.order_id, e.what());
        return false;
    }
}

/**
 * @brief 处理订单簿更新
 * @param book 更新后的订单簿
 * @details 更新内部维护的订单簿数据
 */
void SmartOrderRouter::onOrderBookUpdate(const OrderBook& book) {
    std::lock_guard<std::mutex> lock(books_mutex_);
    order_books_[book.getSymbol()] = book;
}

/**
 * @brief 设置最大允许滑点
 * @param max_slippage 最大滑点比例
 */
void SmartOrderRouter::setMaxSlippage(double max_slippage) {
    max_slippage_ = max_slippage;
}

/**
 * @brief 设置最小流动性要求
 * @param min_liquidity 最小流动性数量
 */
void SmartOrderRouter::setMinLiquidity(int64_t min_liquidity) {
    min_liquidity_ = min_liquidity;
}

/**
 * @brief 检查订单的流动性是否满足要求
 * @param order 待检查的订单
 * @param book 订单簿数据
 * @return 如果流动性满足要求返回true，否则返回false
 */
bool SmartOrderRouter::checkLiquidity(const Order& order, const OrderBook& book) {
    const auto& levels = (order.side == OrderSide::BUY) ? book.getAsks() : book.getBids();
    int64_t available_liquidity = 0;
    
    // 计算可用流动性
    for (const auto& level : levels) {
        if ((order.side == OrderSide::BUY && level.price > order.price) ||
            (order.side == OrderSide::SELL && level.price < order.price)) {
            break;
        }
        available_liquidity += level.quantity;
    }
    
    return available_liquidity >= min_liquidity_;
}

/**
 * @brief 检查订单的滑点是否在允许范围内
 * @param order 待检查的订单
 * @param book 订单簿数据
 * @return 如果滑点在允许范围内返回true，否则返回false
 */
bool SmartOrderRouter::checkSlippage(const Order& order, const OrderBook& book) {
    double best_price = (order.side == OrderSide::BUY) ? book.getBestAsk() : book.getBestBid();
    double price_diff = std::abs(order.price - best_price);
    double slippage = price_diff / best_price;
    
    return slippage <= max_slippage_;
}

/**
 * @brief 订单管理器构造函数
 * @param executor 订单执行器指针
 */
OrderManager::OrderManager(std::shared_ptr<OrderExecutor> executor)
    : executor_(executor)
    , order_counter_(0)
{}

/**
 * @brief 下单
 * @param order 订单信息
 * @return 订单ID
 * @details 生成订单ID并提交订单，更新订单状态
 */
std::string OrderManager::placeOrder(const Order& order) {
    std::lock_guard<std::mutex> lock(orders_mutex_);
    
    // 创建新订单
    Order new_order = order;
    new_order.order_id = generateOrderId();
    new_order.status = OrderStatus::PENDING;
    new_order.timestamp = std::chrono::system_clock::now();
    
    // 保存订单信息
    active_orders_[new_order.order_id] = new_order;
    
    // 提交订单
    if (executor_->submitOrder(new_order)) {
        new_order.status = OrderStatus::SUBMITTED;
        active_orders_[new_order.order_id] = new_order;
    } else {
        new_order.status = OrderStatus::REJECTED;
        active_orders_[new_order.order_id] = new_order;
    }
    
    return new_order.order_id;
}

/**
 * @brief 取消订单
 * @param order_id 订单ID
 * @return 如果订单成功取消返回true，否则返回false
 */
bool OrderManager::cancelOrder(const std::string& order_id) {
    std::lock_guard<std::mutex> lock(orders_mutex_);
    
    auto it = active_orders_.find(order_id);
    if (it == active_orders_.end()) {
        return false;
    }
    
    if (executor_->cancelOrder(order_id)) {
        it->second.status = OrderStatus::CANCELLED;
        return true;
    }
    
    return false;
}

/**
 * @brief 获取订单状态
 * @param order_id 订单ID
 * @return 订单状态
 */
OrderStatus OrderManager::getOrderStatus(const std::string& order_id) {
    std::lock_guard<std::mutex> lock(orders_mutex_);
    
    auto it = active_orders_.find(order_id);
    if (it == active_orders_.end()) {
        return OrderStatus::REJECTED;
    }
    
    return it->second.status;
}

/**
 * @brief 处理订单更新
 * @param order 更新后的订单信息
 * @details 更新内部维护的订单状态
 */
void OrderManager::onOrderUpdate(const Order& order) {
    std::lock_guard<std::mutex> lock(orders_mutex_);
    
    auto it = active_orders_.find(order.order_id);
    if (it != active_orders_.end()) {
        it->second = order;
    }
}

/**
 * @brief 生成订单ID
 * @return 生成的订单ID
 * @details 生成格式为ORD_XXXXXXXX_时间戳的订单ID，使用更高性能的实现
 */
std::string OrderManager::generateOrderId() {
    static std::mutex counter_mutex;
    
    // 获取高精度时间戳(纳秒级)
    auto now = std::chrono::high_resolution_clock::now();
    auto now_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
        now.time_since_epoch()).count();
    
    // 安全递增计数器
    uint32_t counter;
    {
        std::lock_guard<std::mutex> lock(counter_mutex);
        if (order_counter_ == std::numeric_limits<uint32_t>::max()) {
            order_counter_ = 0;
            spdlog::warn("Order counter reset due to overflow");
        }
        counter = order_counter_++;
    }
    
    // 使用fmt库高效格式化
    return fmt::format("ORD_{:08d}_{}", counter, now_ns);
}

bool ExecutionManager::init(const YAML::Node& config) {
    try {
        config_ = config;
        
        // 创建执行引擎
        const auto& engine_config = config["trading"]["execution"]["engine"];
        std::string engine_type = engine_config["type"].as<std::string>();
        
        if (engine_type == "simulation") {
            engine_ = std::make_shared<SimulationEngine>();
            spdlog::info("Using simulation execution engine");
        } else if (engine_type == "ctp") {
            // TODO: 创建CTP执行引擎
            spdlog::info("Using CTP execution engine");
        } else {
            spdlog::error("Unknown execution engine type: {}", engine_type);
            return false;
        }

        // 初始化执行引擎
        if (!engine_->init(config)) {
            spdlog::error("Failed to initialize execution engine");
            return false;
        }

        // 初始化账户信息
        const auto& account_config = config["trading"]["account"];
        account_.balance = account_config["initial_balance"].as<double>();
        account_.available = account_.balance;
        account_.margin = 0.0;
        account_.margin_rate = account_config["margin_rate"].as<double>();

        spdlog::info("Execution manager initialized successfully");
        return true;
    } catch (const std::exception& e) {
        spdlog::error("Failed to initialize execution manager: {}", e.what());
        return false;
    }
}

bool ExecutionManager::start() {
    if (running_) {
        spdlog::warn("Execution manager is already running");
        return true;
    }

    try {
        // 启动执行引擎
        if (!engine_->start()) {
            spdlog::error("Failed to start execution engine");
            return false;
        }

        running_ = true;
        spdlog::info("Execution manager started successfully");
        return true;
    } catch (const std::exception& e) {
        spdlog::error("Failed to start execution manager: {}", e.what());
        return false;
    }
}

void ExecutionManager::stop() {
    if (!running_) {
        spdlog::warn("Execution manager is not running");
        return;
    }

    try {
        // 停止执行引擎
        engine_->stop();
        running_ = false;
        spdlog::info("Execution manager stopped successfully");
    } catch (const std::exception& e) {
        spdlog::error("Failed to stop execution manager: {}", e.what());
    }
}

bool ExecutionManager::submitOrder(const Order& order, ExecutionCallback callback) {
    if (!running_) {
        spdlog::error("Execution manager is not running");
        return false;
    }

    try {
        std::lock_guard<std::mutex> lock(mutex_);

        // 检查订单参数
        const auto& params = config_["trading"]["trading"]["params"];
        if (order.volume < params["min_volume"].as<double>() ||
            order.volume > params["max_volume"].as<double>()) {
            spdlog::error("Invalid order volume: {}", order.volume);
            return false;
        }

        // 检查资金
        double required_margin = order.price * order.volume * account_.margin_rate;
        if (required_margin > account_.available) {
            spdlog::error("Insufficient margin: required={}, available={}", 
                         required_margin, account_.available);
            return false;
        }

        // 提交订单
        if (!engine_->submitOrder(order, [this](const ExecutionResult& result) {
            this->processExecutionResult(result);
        })) {
            spdlog::error("Failed to submit order: {}", order.order_id);
            return false;
        }

        // 保存回调
        if (callback) {
            order_callbacks_[order.order_id] = callback;
        }

        spdlog::info("Order submitted successfully: {}", order.order_id);
        return true;
    } catch (const std::exception& e) {
        spdlog::error("Failed to submit order: {}", e.what());
        return false;
    }
}

bool ExecutionManager::cancelOrder(const std::string& order_id) {
    if (!running_) {
        spdlog::error("Execution manager is not running");
        return false;
    }

    try {
        std::lock_guard<std::mutex> lock(mutex_);

        // 检查订单状态
        auto status = engine_->getOrderStatus(order_id);
        if (status == ExecutionStatus::FILLED ||
            status == ExecutionStatus::CANCELLED ||
            status == ExecutionStatus::REJECTED) {
            spdlog::warn("Cannot cancel order in status: {}", static_cast<int>(status));
            return false;
        }

        // 取消订单
        if (!engine_->cancelOrder(order_id)) {
            spdlog::error("Failed to cancel order: {}", order_id);
            return false;
        }

        spdlog::info("Order cancelled successfully: {}", order_id);
        return true;
    } catch (const std::exception& e) {
        spdlog::error("Failed to cancel order: {}", e.what());
        return false;
    }
}

ExecutionStatus ExecutionManager::getOrderStatus(const std::string& order_id) const {
    std::lock_guard<std::mutex> lock(mutex_);
    return engine_->getOrderStatus(order_id);
}

std::vector<ExecutionResult> ExecutionManager::getOrderHistory(const std::string& order_id) const {
    std::lock_guard<std::mutex> lock(mutex_);
    auto it = order_history_.find(order_id);
    if (it == order_history_.end()) {
        return {};
    }
    return it->second;
}

Position ExecutionManager::getPosition(const std::string& symbol) const {
    std::lock_guard<std::mutex> lock(mutex_);
    auto it = positions_.find(symbol);
    if (it == positions_.end()) {
        return Position{symbol, 0.0, 0.0, 0.0, 0.0};
    }
    return it->second;
}

Account ExecutionManager::getAccount() const {
    std::lock_guard<std::mutex> lock(mutex_);
    return account_;
}

void ExecutionManager::processExecutionResult(const ExecutionResult& result) {
    std::lock_guard<std::mutex> lock(mutex_);

    // 更新订单历史
    order_history_[result.order_id].push_back(result);

    // 更新持仓信息
    updatePosition(result);

    // 更新账户信息
    updateAccount(result);

    // 调用回调
    auto it = order_callbacks_.find(result.order_id);
    if (it != order_callbacks_.end()) {
        try {
            it->second(result);
        } catch (const std::exception& e) {
            spdlog::error("Error in order callback: {}", e.what());
        }

        // 如果订单已完成，移除回调
        if (result.status == ExecutionStatus::FILLED ||
            result.status == ExecutionStatus::CANCELLED ||
            result.status == ExecutionStatus::REJECTED) {
            order_callbacks_.erase(it);
        }
    }
}

void ExecutionManager::updatePosition(const ExecutionResult& result) {
    auto& position = positions_[result.symbol];
    position.symbol = result.symbol;

    if (result.direction == OrderDirection::BUY) {
        position.long_volume += result.volume;
        position.long_price = (position.long_price * (position.long_volume - result.volume) +
                             result.price * result.volume) / position.long_volume;
    } else {
        position.short_volume += result.volume;
        position.short_price = (position.short_price * (position.short_volume - result.volume) +
                              result.price * result.volume) / position.short_volume;
    }
}

void ExecutionManager::updateAccount(const ExecutionResult& result) {
    // 计算交易成本
    double cost = result.price * result.volume;
    double fee = cost * config_["trading"]["trading"]["params"]["fee_rate"].as<double>();

    // 更新账户信息
    if (result.direction == OrderDirection::BUY) {
        account_.available -= (cost + fee);
        account_.margin += cost * account_.margin_rate;
    } else {
        account_.available += (cost - fee);
        account_.margin -= cost * account_.margin_rate;
    }
}

} // namespace hft 